﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using work_log.worklogservices;
using work_log.userservices;
using System.Threading;
using System.Diagnostics;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid.Columns;
using DevComponents.DotNetBar;
using System.Reflection;

namespace work_log {
    public partial class frmMain : DevExpress.XtraEditors.XtraForm {
        /// <summary>
        /// UI线程同步上下文
        /// </summary>
        SynchronizationContext mainContext = null;
        /// <summary>
        /// 是否点击了检查更新
        /// </summary>
        bool IsClick = false;
        public frmMain() {
            InitializeComponent();
            //获取UI线程同步上下文
            mainContext = SynchronizationContext.Current;
        }

        private void btnAbout_Click(object sender, EventArgs e) {
            frmAbout frm = new frmAbout();
            frm.ShowDialog();
        }

        private void frmMain_Load(object sender, EventArgs e) {
            //清空默认的tab
            stMenu.Tabs.Clear();
            tool_ItemDetail_Click(null, null);

            this.rbnMenManage.Select();

            this.barName.Caption = UserInfo.uName;
            this.barTime.Caption = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss");

            bsVersion.Caption = new IniClass(Application.StartupPath + @"\update.ini").IniReadValue("update", "version");

            timer1.Start();
        }

        #region 按钮
        private void buttonItem16_Click(object sender, EventArgs e) {
            XtraMessageBox.Show("更多功能尽请期待！！！", "温馨提示");
        }

        #region 窗体关闭、注销
        private void btnExit_Click(object sender, EventArgs e) {
            if (DevExpress.XtraEditors.XtraMessageBox.Show("是否退出当前系统？", "温馨提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) {
                Application.Exit();
            }
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e) {
            if (e.CloseReason == CloseReason.UserClosing) {
                if (DevExpress.XtraEditors.XtraMessageBox.Show("是否退出当前系统？", "温馨提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) {
                    Application.Exit();
                    return;
                }
                e.Cancel = true;
            }
        }

        private void btnZXSystem_Click(object sender, EventArgs e) {
            //this.Close();
            Process mainProcess = new Process();
            mainProcess.StartInfo.FileName = Application.ExecutablePath.Trim();
            mainProcess.Start();
            Process.GetCurrentProcess().Kill();

        }
        #endregion

        private void btnEditPwd_Click(object sender, EventArgs e) {
            frmPassword frmPwd = new frmPassword();
            frmPwd.ShowDialog();
        }

        private void buttonItem15_Click(object sender, EventArgs e) {
            SetMdiForm("日志查询", typeof(frmLogs));
        }
        #endregion

        #region Add Click
        private void tool_ItemDetail_Click(object sender, EventArgs e) {
            SetMdiForm("日志查询", typeof(frmLogs));
        }

        /// <summary>
        /// 打开窗体
        /// </summary>
        /// <param name="caption">标题</param>
        /// <param name="formType">窗口类型</param>
        public void SetMdiForm(string caption, Type formType) {
            bool IsOpened = false;

            //遍历所有的Tab页面，如果存在，那么设置为选中即可
            foreach (SuperTabItem tabItem in stMenu.Tabs) {
                if (tabItem.Name == caption) {
                    stMenu.SelectedTab = tabItem;
                    IsOpened = true;
                    break;
                }
            }

            if (!IsOpened) {
                //为了方便管理，通过反射动态创建窗体
                //然后分配给SuperTab控件，创建一个SuperTabItem并显示
                stMenu.Visible = true;
                Assembly ass = Assembly.GetExecutingAssembly();
                DevExpress.XtraEditors.XtraForm frm = ass.CreateInstance(formType.FullName) as DevExpress.XtraEditors.XtraForm;

                SuperTabItem tabItem = stMenu.CreateTab(caption);
                tabItem.Name = caption;
                tabItem.Text = caption;

                frm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                frm.TopLevel = false;
                frm.Visible = true;
                frm.Dock = DockStyle.Fill;
                tabItem.AttachedControl.Controls.Add(frm);

                stMenu.SelectedTab = tabItem;
            }
        }

        private void ctx_Window_CloseAll_Click(object sender, EventArgs e) {
            CloseAllDocuments();
        }

        private void ctx_Window_CloseOther_Click(object sender, EventArgs e) {
            CloseOthers();
        }

        #region 窗口关闭
        /// <summary>
        /// 关闭所有窗口
        /// </summary>
        public void CloseAllDocuments() {
            if (stMenu.Tabs.Count == 0) this.stMenu.Visible = false;
            //循环获取窗口
            for (int i = stMenu.Tabs.Count - 1; i >= 0; i--) {
                SuperTabItem tabItem = stMenu.Tabs[i] as SuperTabItem; //获取子窗口
                if (tabItem != null) {//子窗口不等于空
                    tabItem.Close();//关闭
                }
            }
        }

        /// <summary>
        /// 关闭除此之外的所有窗口
        /// </summary>
        public void CloseOthers() {
            //判断当前激活窗口是否为空
            if (ActiveMdiChild != null) {
                //获取当前窗口的类型
                Type formType = ActiveMdiChild.GetType();
                //循环tab控件中的所有窗口
                for (int i = stMenu.Tabs.Count - 1; i >= 0; i--) {
                    SuperTabItem tabItem = stMenu.Tabs[i] as SuperTabItem; //获取子窗口
                    if (tabItem != null && formType != tabItem.AttachedControl.Controls[0].GetType()) {
                        tabItem.Close();
                    }
                }
            }
        }
        #endregion

        private void timer1_Tick(object sender, EventArgs e) {
            this.barTime.Caption = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss");
        }

        private void update() {
            mainSafeOpertion(null);
        }
        #endregion

        #region Thread Opertion
        /// <summary>
        /// 线程间的安全操作
        /// </summary>
        /// <param name="sender"></param>
        private void mainSafeOpertion(object sender) {
            try {
                IniClass ini = new IniClass(Application.StartupPath + @"\update.ini");
                //升级服务
                UpdateSerivce.UpdateSerivceSoapClient updateService = new UpdateSerivce.UpdateSerivceSoapClient();
                //客户端版本
                string clientVersion = ini.IniReadValue("update", "version");
                //服务端版本号
                string serviceVersion = updateService.GetVersion(Guid.Empty);
                if (clientVersion != serviceVersion) {
                    DialogResult dialogResult = XtraMessageBox.Show("有新版本，是否更新？", "升级", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                    if (dialogResult == System.Windows.Forms.DialogResult.Yes) {
                        Application.Exit();
                        Process.Start("AutoUpdater.exe");
                    }
                } else {
                    if (IsClick) {
                        XtraMessageBox.Show("当前已是最新版！");
                    }
                }
            } catch (Exception ex) {
                if (ex.Message == "系统找不到指定的文件。") {
                    XtraMessageBox.Show("客户端缺少必要文件，请去官网重新下载！");
                }
            }
        }
        #endregion

        private void frmMain_Shown(object sender, EventArgs e) {
            Thread mainThread = new Thread(new ThreadStart(this.update));
            mainThread.Start();
        }

        private void barChekUpdate_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
            IsClick = true;
            Thread mainThread = new Thread(new ThreadStart(this.update));
            mainThread.Start();
        }

        private void stMenu_ControlBox_MouseDown(object sender, MouseEventArgs e) {

        }

        private void stMenu_TabStripMouseDown(object sender, MouseEventArgs e) {
            //if (e.Button == System.Windows.Forms.MouseButtons.Right) {
            //    Point pt = new Point(e.X, e.Y);
            //    Rectangle recTab = stMenu.SelectedTab.ContentRectangle;
            //    if (recTab.Contains(pt)) {
            //        XtraMessageBox.Show("123");
            //    }
            //}
        }

        private void stMenu_MeasureTabItem(object sender, SuperTabMeasureTabItemEventArgs e) {
        }

        private void stMenu_ControlBox_MouseDown_1(object sender, MouseEventArgs e) {
            //MessageBox.Show("23");
        }
    }
}